﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MP3Ganizer.Common.Interfaces.FileList;
using Microsoft.Practices.ServiceLocation;
using System.Windows.Controls;
using System.Windows;
using MP3Ganizer.BusinessObject.Hierarchy;

namespace MP3Ganizer.Modules.FileList.Views
{
    [TemplatePart(Name = "PART_lstFile", Type = typeof(ItemsControl))]
    class FileListView : ContentControl, IFileListView
    {
        private ItemsControl _lstFile;

        public FileListView()
        {
            DataContext = ServiceLocator.Current.GetInstance<IFileListViewModel>();
        }
        public IFileListViewModel ViewModel
        {

            get { return (IFileListViewModel)DataContext; }
        }

        public override void OnApplyTemplate()
        {
            _lstFile = base.GetTemplateChild("PART_lstFile") as ItemsControl;
            if (_lstFile != null)
            {
                _lstFile.DragOver += new DragEventHandler(OnDragOver);
                _lstFile.Drop += new DragEventHandler(OnDrop);
            }
        }

        void OnDragOver(object sender, DragEventArgs e)
        {
            e.Effects = e.Data.GetDataPresent(typeof(IEnumerable<IFileModel>)) ? System.Windows.DragDropEffects.Copy : System.Windows.DragDropEffects.None;
        }

        void OnDrop(object sender, DragEventArgs e)
        {
            bool dataProcessed = false;
            foreach (var key in e.Data.GetFormats())
            {
                var data = e.Data.GetData(key);
                if (data is IEnumerable<IFileModel>)
                {
                    e.Effects = System.Windows.DragDropEffects.Copy;
                    IEnumerable<IFileModel> fileList = data as IEnumerable<IFileModel>;
                    fileList.ToList().ForEach( item => this.ViewModel.List.Add(item));
                    dataProcessed = true;
                    break;
                }
            }
            if (!dataProcessed)
                e.Effects = System.Windows.DragDropEffects.None;
            e.Handled = true;
        }
    }
}
